package servlet;

import com.alibaba.fastjson.JSON;
import entity.Msg;
import entity.Product;
import service.IProductService;
import service.imp.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Jiuyuesheng
 * @date 2019/12/30  15:53
 */

public class ProductServlet extends HttpServlet {
    private IProductService productService = new ProductService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");

//        response.setContentType("text/html;charset=UTF-8");
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        String method = request.getParameter("method");

        if("queryAll".equals(method)){
            doQueryAll(request,response);
        }else if("likeQuery".equals(method)){
            doLikeQuery(request,response);
        }
    }

    private void doQueryAll(HttpServletRequest request, HttpServletResponse response) {
        Msg msg = new Msg();
        List<Product> products = productService.queryAllProduct();
        msg.setData(products);
        try {
            response.getWriter().print(JSON.toJSONString(msg));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doLikeQuery(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        List<Product> products = productService.queryAllProductByName(name);
        Msg msg = new Msg();
        msg.setStatus(200);
        msg.setData(products);
        try {
            response.getWriter().print(JSON.toJSONString(msg));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
